import os
import datetime
import time
from ftplib import FTP
import subprocess, shlex, re

def CreateAndStoreBackup(Name):
    print 'Creating'
    COOPIPBackupLocation='/opt/coopipbackup/'
    os.system("rmdir -R " + COOPIPBackupLocation) 
    os.system("mkdir " + COOPIPBackupLocation) 
    os.system("chmod -R 777 " + COOPIPBackupLocation) 
    BackupName='COOPIPBackup_' #+ str(datetime.datetime.today())[:10].replace('-','_')
    BackupFolderName=COOPIPBackupLocation + 'TemporaryBackupFolder/'
    os.system("mkdir " + BackupFolderName)
    os.system("chmod -R 777 " + BackupFolderName) 
    os.system("pg_dump coopip > " + COOPIPBackupLocation + "coopip.sql")
    os.system("pg_dump redmine > " + COOPIPBackupLocation + "redmine.sql")
    os.system("cp -R /opt " + BackupFolderName)
    os.system("cp -R /etc/apache2 " + BackupFolderName)
    os.system("cp -R /etc/postgresql " + BackupFolderName)
    os.system("cp -R /scripts " + BackupFolderName)
    os.system("chmod -R 777 " + BackupFolderName) 
    os.system("tar cvzf " + COOPIPBackupLocation + BackupName + '.tgz ' + BackupFolderName)
    os.system("chmod -R 777 " + COOPIPBackupLocation + BackupName + '.tgz ')
    os.system("rm -R " + BackupFolderName)
    print 'Storing'
    os.system('wput --binary -u /opt/coopipbackup/' + Name + ' ftp://ipbackup:ipbackup5123512@192.168.100.8')
    os.system('wput --binary -u /opt/coopipbackup/coopip.sql ftp://ipbackup:ipbackup5123512@192.168.100.8')
    os.system('wput --binary -u /opt/coopipbackup/redmine.sql ftp://ipbackup:ipbackup5123512@192.168.100.8')

def GetRemoteFileInformation(Name):
    ftp=FTP('192.168.100.8')
    ftp.login('ipbackup','ipbackup5123512')
    ftp.cwd('/opt/coopipbackup')
    FileSize = ftp.size(Name)
    DirectoryList=[]
    ftp.dir(DirectoryList.append)
    ftp.quit()
    for entry in DirectoryList:
        if Name in entry:
            start=entry.find(str(FileSize)) + len(str(FileSize)) + 1
            end=len(Name) + 1
            DateString=entry[start:-end]
            break
    LastModifiedDateTime=datetime.datetime.strptime(str(datetime.datetime.now().year) + DateString,'%Y%b %d %H:%M')
    return (LastModifiedDateTime, FileSize)

def GetBackupStatus(BackupName, RemoteDateTime, RemoteSize):
    Dict={}
    LocalTimeStamp=os.path.getmtime('/opt/coopipbackup/' + BackupName)
    LocalDateTime=datetime.datetime.fromtimestamp(LocalTimeStamp)
    Dict['BackupLocalDateTime']=LocalDateTime.strftime('%Y%m%d_%H%M')
    LocalSize=os.stat('/opt/coopipbackup/' + BackupName).st_size    
    Dict['BackupLocalSize']=LocalSize
    Dict['BackupRemoteDateTime']=RemoteDateTime.strftime('%Y%m%d_%H%M')
    Dict['BackupRemoteSize']=RemoteSize
    return Dict

def GetLocalStatus():
    Dict={}
    Dict['ServerName']='COOPIP'
    #size in bytes = block size * blocks
    DiskInfo = os.statvfs('/')
    DriveTotalInBytes=DiskInfo.f_bsize * DiskInfo.f_blocks
    Dict['Drivevda1TotalSpace']=DriveTotalInBytes
    DriveFreeInBytes=DiskInfo.f_bsize * DiskInfo.f_bavail
    Dict['Drivevda1FreeSpace']=DriveFreeInBytes
    
    Output=subprocess.check_output(shlex.split('free')).split('\n')
    MemoryTotal=re.split('\s+',Output[1])[1]
    MemoryFree=re.split('\s+',Output[2])[3]
    Swap=re.split('\s+',Output[3])
    Dict['TotalMemory']=MemoryTotal
    Dict['FreeMemory']=MemoryFree
    Dict['TotalSwap']=Swap[1]
    Dict['FreeSwap']=Swap[3]
    return Dict

def SendStatusToCOOPIP(Dict):
    ServerUpdateURL = 'http://192.168.100.54/coopip/serverstatusupdate/'
    DataString=str(Dict).replace('{','').replace('}','').replace(' ','').replace("'",'')
    os.system('wget ' + ServerUpdateURL + DataString + ' -o /dev/null -O /dev/null')


BackupName='COOPIPBackup_.tgz'
CreateAndStoreBackup(BackupName)
BackupRemoteDateTime, BackupRemoteSize=GetRemoteFileInformation(BackupName)
StatusDict=GetLocalStatus()
StatusDict2=GetBackupStatus(BackupName, BackupRemoteDateTime,BackupRemoteSize)
StatusDict.update(StatusDict2)
print 'Logging'
SendStatusToCOOPIP(StatusDict)
